<template>
  <div class="feature-popup" ref="popupEl">
    <div class="popup-closer" @click="closePopup">×</div>
    <!-- 默认内容插槽 -->
    <div class="custom-popup" v-if="filteredProperties">
      <!-- 标题区域 -->
      <div class="popup-header">
        <el-tag effect="dark" class="marker-tag"
          :class="{ 'blinking': !filteredProperties.marked, 'marked-tag': filteredProperties.marked }"
          :type="filteredProperties.marked ? 'info' : 'success'" size="mini" @click="handlerMarker">
          {{ filteredProperties.marked ? '已标记' : '进行标记' }}
        </el-tag>
        <h3 class="title">{{ filteredProperties.name || '未命名要素' }}</h3>
      </div>
      <!-- 属性表格 -->
      <el-descriptions :column="1" class="property-table">
        <el-descriptions-item label="类别">
          <span class="highlight-text">{{ filteredProperties.category }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="经纬度" v-if="filteredProperties.location">
          <span class="highlight-text">{{ filteredProperties.location }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="面积" v-if="filteredProperties.area && filteredProperties.area">
          <div class="area-display">
            <span class="area-value">{{ filteredProperties.area.km }}</span>
            <span class="area-unit">平方公里</span>
            <el-divider direction="vertical" />
            <span class="area-value">{{ filteredProperties.area?.mu }}</span>
            <span class="area-unit">亩</span>

          </div>
        </el-descriptions-item>
        <!-- 扩展属性 -->
        <el-descriptions-item v-for="(item, idx) of findAllIndexData(filteredProperties.departName)" :key="idx"
          :label="item.indexName">
          <el-tag type="success">{{ item.name }} {{ item.value }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <!-- 空状态提示 -->
    </div>
    <div v-if="!filteredProperties" class="empty-tip">
      <i class="el-icon-warning-outline"></i>
      暂无详细属性信息
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { Getter } from 'vuex-class';
declare const AMap: any;
@Component
export default class FeaturePopup extends Vue {
  @Prop({ required: true }) map!: any;
  @Prop({ default: null }) feature!: any;
  @Prop({ default: '要素详情' }) featureTitle!: string;
  @Prop({ default: () => [] }) excludeKeys!: string[];
  @Getter private indexData;
  private popupPosition: [number, number] = [0, 0];
  private currentFeature: any = null;
  private overlayWindow: any;
  private currentOverlay: any;


  initOverlay() {
    AMap.plugin(['AMap.InfoWindow', 'AMap.LngLat', 'AMap.GeometryUtil'], () => { //异步加载插件
      this.overlayWindow = new AMap.InfoWindow({
        isCustom: true,
        content: this.$refs.popupEl as HTMLElement,
        offset: new AMap.Pixel(16, -45)
      });
    });
  }

  mounted() {
    this.initOverlay();
  }


  get findAllIndexData() {
    const data = this.indexData;
    return function (name: string) {
      if (!data) return [];
      const matched = data
        ?.flatMap((cat: any) => cat.data || [])
        ?.filter((item: any) => item.departName == name);

      return matched ? matched : [];
    }
  }

  get filteredProperties() {

    if (!this.currentFeature || !this.currentFeature.properties) return {};

    let rs = Object.entries(this.currentFeature.properties)
      .filter(([key]) => !this.excludeKeys.includes(key))
      .reduce((obj, [key, value]) => {
        obj[key] = value;
        return obj;
      }, {} as Record<string, any>);

    return rs;
  }

  handlerMarker() {
    const properties = this.currentOverlay?.getExtData();
    if (properties.marked) {
      this.$message.info("该要素已标记过");
      return
    }
    if(this.currentFeature){
      this.currentFeature.properties.marked = true;
    }

    this.$emit('create-feature', this.currentOverlay, properties)
    properties.marked = true;
  }

  closePopup() {
    this.overlayWindow.close();
    this.$emit('close');
  }

  get popupStyle() {
    return {
      left: this.popupPosition[0] + 'px',
      top: this.popupPosition[1] + 'px'
    };
  }

  public showOverlay(overlay) {
    this.showPopup({ properties: overlay.getExtData() }, overlay);
  }


  public showPopup(feature: any, overlay) {
    this.currentFeature = feature;
    this.currentOverlay = overlay;
    const type = overlay.CLASS_NAME;
    console.log(this.currentFeature);
    let toLocation: [number, number] = [0, 0];

    switch (type) {
      case "AMap.Marker": {
        const pos = overlay.getPosition();
        toLocation = [pos.lng, pos.lat];
        break;
      }
      case "AMap.Polygon": {
        const bounds = overlay.getBounds();
        toLocation = [bounds.getSouthWest().lng, bounds.getNorthEast().lat];
        break;
      }
      case "Overlay.Polygon": {
        const bounds = overlay.getBounds();
        toLocation = [bounds.getSouthWest().lng, bounds.getNorthEast().lat];
        break;
      }
    }

    this.overlayWindow.open(this.map, toLocation);
    this.currentOverlay.on('click', () => {
      this.overlayWindow.open(this.map, toLocation);
    });
    this.map.setCenter(toLocation);
    this.map.setZoom(15);
  }

  @Watch('feature')
  onFeatureChanged(newFeature: any) {
    if (newFeature) {
      this.currentFeature = newFeature;
    }
  }
}
</script>

<style scoped>
.feature-popup {
  background: #ffffff;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.16);
  min-width: 280px;
  max-width: 300px;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  position: relative;
  border: 1px solid #eaeaea;
  color: #333;
}

.popup-closer {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 22px;
  color: #999;
  width: 24px;
  height: 24px;
  text-align: center;
  line-height: 24px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 50%;
}

.popup-closer:hover {
  color: #ff4444;
  background: #f8f8f8;
  transform: scale(1.1);
}

.header {
  padding-right: 18px;
  /* 避免被关闭按钮覆盖 */
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 12px;
}

.title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #1a73e8;
}

.properties {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 4px;
}

/* 滚动条样式 */
.properties::-webkit-scrollbar {
  width: 6px;
}

.properties::-webkit-scrollbar-track {
  background: #f8f8f8;
  border-radius: 4px;
}

.properties::-webkit-scrollbar-thumb {
  background: #d0d0d0;
  border-radius: 4px;
}

.property-item {
  padding: 10px 0;
  display: flex;
  border-bottom: 1px solid #f5f5f5;
  line-height: 1.5;
}

.property-item:last-child {
  border-bottom: none;
}

.property-key {
  flex: 0 0 40%;
  font-weight: 500;
  color: #666;
}

.property-value {
  flex: 1;
  color: #222;
  font-weight: 400;
  word-break: break-word;
  padding-left: 8px;
}

.empty-tip {
  text-align: center;
  padding: 20px 10px;
  color: #888;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.empty-tip p {
  margin: 0;
  font-size: 14px;
}

.property-table {
  font-size: 12px;
}

.marked {
  cursor: pointer;
}

@keyframes blink {
  0% {
    opacity: 1;
    transform: scale(1);
  }

  50% {
    opacity: 0.7;
    transform: scale(1.05);
    box-shadow: 0 0 10px #67C23A;
  }

  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.marker-tag {
  transition: all 0.3s ease;
  cursor: pointer;
}

/* 未标记状态 - 闪烁效果 */
.blinking {
  animation: blink 1.5s infinite;
}

/* 已标记状态 - 灰色样式 */
.marked-tag {
  cursor: default;
  background-color: #909399;
  border-color: #909399;
}

/* 鼠标悬停时停止闪烁 */
.blinking:hover {
  animation: none;
  transform: scale(1.05);
  box-shadow: 0 0 8px rgba(103, 194, 58, 0.6);
}
</style>